﻿using DtoFw;
using Repository;
using Service.Base;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Domain.Entity;
using DtoFw.Query;
using Repository.Base;
using System.Collections;

namespace Service
{
    /// <summary>
    /// 盘点
    /// </summary>
    public class CasePhysicalPanDianService : BaseService
    {
        private readonly CasePhysicalPanDianRepository _casePhysicalPanDianRepository;
        private readonly CasePhysicalEvidenceRepository _casePhysicalEvidenceRepository;


        public CasePhysicalPanDianService(CasePhysicalPanDianRepository casePhysicalPanDianRepository, CasePhysicalEvidenceRepository casePhysicalEvidenceRepository, MainSerialNumberRepository mainSerialNumberRepository) : base(mainSerialNumberRepository)
        {
            this._casePhysicalPanDianRepository = casePhysicalPanDianRepository;
            this._casePhysicalEvidenceRepository = casePhysicalEvidenceRepository;
        }

        /// <summary>
        /// 新增
        /// </summary>
        public BaseResult Post(BaseQuery reqDto)
        {
            var entity = new CasePhysicalPanDianEntity()
            {
                Title = reqDto.Name,
                Status = 0,
                Remark = "",
                OrganId = reqDto.OrganId,
                CreateTime = DateTime.Now,
                Creator = reqDto.UserName,
                CreatorId = reqDto.UserId,
                Modifyer = reqDto.UserName,
                ModifyerId = reqDto.UserId,
                ModifyerTime = DateTime.Now
            };
            var lst = this._casePhysicalEvidenceRepository.Query(v => v.IsDeleted == false && reqDto.Ids.Contains(v.Id)).ToList();
            entity.Title = reqDto.Name;
            entity.Attrs = Newtonsoft.Json.JsonConvert.SerializeObject(lst.Select(v => new { id = v.Id, st = 0 }).ToList());
            _casePhysicalPanDianRepository.Insert(entity);
            return BaseResult.Succeed();
        }

        public Pager<object> QueryList(CaseQueryDto reqDto)
        { 
            int total = 0;
            var sql = $@"select s2.*
                           from case_physical_pandian s2 
                          where s2.IsDeleted=0 AND OrganId in({reqDto.OrganId}) ";
            if (!string.IsNullOrEmpty(reqDto.CaseName))
                sql += $" AND s2.Title like '%{reqDto.CaseName}%' ";
            if (!string.IsNullOrEmpty(reqDto.Status))
                sql += $" AND s2.`Status`={reqDto.Status} ";
            if (reqDto.CaseTimeStart.HasValue)
                sql += $" AND s2.CreateTime >='{reqDto.CaseTimeStart.Value.ToString("yyyy-MM-dd")}' ";
            if (reqDto.CaseTimeEnd.HasValue)
                sql += $" AND s2.CreateTime <='{reqDto.CaseTimeEnd.Value.ToString("yyyy-MM-dd")} 23:59:59' ";
            var r = this._casePhysicalPanDianRepository.GetDb().SqlQueryable<dynamic>(sql).ToPageList(reqDto.Page, reqDto.PageSize, ref total);
            return new Pager<object>()
            {
                TotalCount = total,
                Data = r
            };
        }

        public Pager<object> QueryPanDianDetail(CaseQueryDto reqDto)
        {
            var inf = this._casePhysicalPanDianRepository.Query(v => v.Id == reqDto.Id).FirstOrDefault();
            var lst1 = inf.Items.Select(v => v.id).ToList();
            var lst = this._casePhysicalEvidenceRepository.Query(v => v.IsDeleted == false && lst1.Contains(v.Id)).ToList();

            var lstRet = new List<object>();
            foreach (var item in lst)
            {
                var t = inf.Items.FirstOrDefault(v => v.id == item.Id);
                lstRet.Add(new
                {
                    item.No,
                    item.Name,
                    item.Quantity,
                    item.Status,
                    item.Location,
                    PdSt = t != null && t.st == 1 ? "在库" : "未在库"
                });
            }

            return new Pager<object>()
            {
                TotalCount = lst1.Count,
                Data = lstRet
            };
        }
        public BaseResult DeletePanDianTask(BaseQuery reqDto)
        {
            var lstRet = new List<object>();
            foreach (var _id in reqDto.Ids)
            {
                var inf = this._casePhysicalPanDianRepository.Query(v => v.Id == _id).FirstOrDefault();
                inf.IsDeleted = true;
                inf.Modifyer = reqDto.UserName;
                inf.ModifyerId = reqDto.UserId;
                inf.ModifyerTime = DateTime.Now;
                this._casePhysicalPanDianRepository.Update(inf);
            }
            return BaseResult.Succeed();
        }
        #region 盘点任务
        /// <summary>
        /// 盘点任务下载
        /// </summary>
        public List<PanDianTaskEntity> GetTasks(long organid)
        {
            var tasks = new List<PanDianTaskEntity>();
            //查询盘点任务
            var lst = this._casePhysicalPanDianRepository.Query(v => v.Status == 0 && v.IsDeleted == false && v.OrganId == organid);
            foreach (var item in lst)
            {
                var ids = item.Items.Select(v => v.id).ToList();
                //明细
                var details = this._casePhysicalPanDianRepository.GetTaskDetails(ids);

                tasks.Add(new PanDianTaskEntity
                {
                    name = item.Title,
                    type = 0,
                    planTime = item.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    relationId = item.Id.ToString(),
                    details = details
                });
                item.Status = 1;
                item.ModifyerTime = DateTime.Now;
                //修改同步状态
                _casePhysicalPanDianRepository.Update(item);
            }
            return tasks;
        }
        /// <summary>
        /// 盘点结果上报
        /// </summary>
        public bool PanDianReport(List<PanDianTaskEntity> list)
        {
            foreach (var item in list)
            {
                var inf = this._casePhysicalPanDianRepository.Query(v => v.Id == Convert.ToInt64(item.relationId)).FirstOrDefault();
                if (inf == null)
                    continue;

                foreach (var row in item.details)
                {
                    var evi = this._casePhysicalEvidenceRepository.Query(v => v.IsDeleted == false && (v.No == row.epc)).FirstOrDefault();
                    if (evi != null)
                    {
                        var t = inf.Items.FirstOrDefault(v => v.id == evi.Id);
                        t.st = row.status;
                    }
                }


                inf.Status = 2;
                inf.Attrs = Newtonsoft.Json.JsonConvert.SerializeObject(inf.Items);
                _casePhysicalPanDianRepository.Update(inf);
            }
            return true;
        }

        #endregion 盘点任务
    }
}

